package labuladong.leetcode.editor.cn._03binarytree.ch00;

public class _104_MaximumDepthOfBinaryTree {

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    /***** 解法一，回溯算法思路 *****/
    class Solution {

        int depth = 0;
        int res = 0;

        public int maxDepth(TreeNode root) {
            traverse(root);
            return res;
        }

        // 遍历二叉树
        void traverse(TreeNode root) {
            if (root == null) {
                return;
            }

            // 前序遍历位置
            depth++;
            if (root.left == null && root.right == null) {
                // 到达叶子节点，更新最大深度
                res = Math.max(res, depth);
            }
//            // 遍历的过程中记录最大深度
//            res = Math.max(res, depth);
            traverse(root.left);
            traverse(root.right);
            // 后序遍历位置
            depth--;
        }
    }

    /***** 解法二，动态规划思路 *****/
    class Solution2 {
        // 定义：输入一个节点，返回以该节点为根的二叉树的最大深度
        public int maxDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftMax = maxDepth(root.left);
            int rightMax = maxDepth(root.right);
            // 根据左右子树的最大深度推出原二叉树的最大深度
            return 1 + Math.max(leftMax, rightMax);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode n4 = new TreeNode(15, null, null);
        TreeNode n5 = new TreeNode(7);
        TreeNode n3 = new TreeNode(20, n4, n5);
        TreeNode n2 = new TreeNode(9);
        TreeNode n1 = new TreeNode(3, n2, n3);

        Solution solution = new _104_MaximumDepthOfBinaryTree().new Solution();
        System.out.println(solution.maxDepth(n1));

        Solution2 solution2 = new _104_MaximumDepthOfBinaryTree().new Solution2();
        System.out.println(solution2.maxDepth(n1));
    }
}
